# 给定以下列表，通过匿名函数和常规函数根据键”age"来排序
classes = [
    {"name": "abyss", "age": 25, "grade": "A"},
    {"name": "kin", "age": 22, "grade": "B"},
    {"name": "tian", "age": 24, "grade": "B"},
    {"name": "hun", "age": 26, "grade": "A"},
    {"name": "exe", "age": 23, "grade": "A"}
]


# 常规函数
def foo(age):
    return age['age']


classes.sort(key=foo)
print(classes)

# 匿名函数
# 升序--默认
my_list = sorted(classes, key=lambda x: int(x['age']))

# 降序
my_list2 = sorted(classes, key=lambda x: int(x['age']), reverse=True)
print(my_list)
print(my_list2)

print("******** 年龄+1 *********")


# 2021年马上要来了，通过map函数将上述同学的age+1
# 结合可变对象
def func(c):
    list_1 = {}
    list_1['age'] = c['age'] + 1
    c.update(list_1)
    return list_1


my_list3 = map(func, classes)
print(list(my_list3))  # [{'age': 23}, {'age': 24}, {'age': 25}, {'age': 26}, {'age': 27}]
print(classes)
# [{'name': 'kin', 'age': 23, 'grade': 'B'}, {'name': 'exe', 'age': 24, 'grade': 'A'}, {'name': 'tian', 'age': 25, 'grade': 'B'}, {'name': 'abyss', 'age': 26, 'grade': 'A'}, {'name': 'hun', 'age': 27, 'grade': 'A'}]


print("*********过滤掉grade是A的同学**********")

# 通过filter函数过滤掉上述同学中grade是A的同学
print(list(filter(lambda x: x['grade'] != 'A', classes)))

print("*********使用递归来重构斐波那契数列**********")


# 使用递归来重构斐波那契数列
class ParamsTypeError(Exception):
    def __init__(self, n):
        self.num = n


# 递归函数
def func_fibo(x):
    if x <= 1:
        return x
    else:
        return func_fibo(x - 1) + func_fibo(x - 2)


def fooc(n):
    for i in range(n):
        print(func_fibo(i))


if __name__ == '__main__':
    try:
        num = input("输入需要几项（正整数）：")
        if not num.isdigit():
            raise ParamsTypeError(num)
        num = int(num)
        if num <= 0:
            print("请输入一个正整数！")
    except ParamsTypeError as p:
        print("ParamsTypeError:请输入正整数！你输入的是：", p.num)
    else:
        if num == 1:
            print("斐波那契数列：")
            print(num-1)
        else:
            print("斐波那契数列：")
            fooc(int(num))
